package com.example.demo.controller;


import com.example.demo.entity.*;
import com.example.demo.model.result;
import com.example.demo.services.MailService;
import com.example.demo.services.ReportService;
import com.example.demo.services.userSecServices;
import com.example.demo.utils.RedisUtil;
import com.github.pagehelper.PageHelper;


import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportService reportService;


    //将封装好的redis类输入到类里面来
    @Autowired
    private RedisUtil redisUtil;

    //如果学生 上报中有问题 老师会打回上报，并且提醒他，上报学院有学生身体出问题了
    @Autowired
    private MailService mailService;

    @Autowired
    private userSecServices userSecServices;


    private Logger logger= LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/getall",method = {RequestMethod.GET})
    public result selectall(){
        logger.info("用户在查询学生们申请记录");
        return result.success(reportService.selectall());
    }


    @RequestMapping(value = "/addSet",method = {RequestMethod.POST})
    public result addSet(@RequestBody Report report, @Param("email")String email){
        logger.info("用户提交信息上报申请");
        reportModel reportModel=new reportModel();
        //这里的id前端直接限制就好了 限制为输入学号的第九位数开始 到倒数第二位数前，如果有000前面就不用写就写你的数字
        //用前端 来 截取数据类型 不知道有没有安全隐患
//        reportModel.setId(report.getId());
        reportModel.setName(report.getName());
        reportModel.setLive(report.getLive());
        reportModel.setHealthy(report.getHealthy());
        reportModel.setNowDate(report.getNowDate());
        reportModel.setEmail(email);
        reportModel.setSec(report.getSec());
        reportModel.setWdo(report.getWdo());
        reportModel.setUserId(report.getUserId());
        //设键值为老师的职工号 在 一个键里面放多个值 就是 不同的 学生
        userAdd teacher=userSecServices.selectUser(report.getUserId());
        String key = String.valueOf(teacher.getTeacherId());
        List<Object> hello = new ArrayList<>();
        hello.add(reportModel);
        //过期时间 设置24个小时 老师 审查 学生的信息上报 时间限制一天内
        boolean test= redisUtil.lSetList(key,hello,86400);
//        long test= redisUtil.sSetAndTime(key,86400,reportModel);

        if(!test){
            return result.fail(CodeMsg.APPLY_ERROR);
        }else {
            logger.info("用户成功提交信息上报");
            //这个地方要注意 我把提交成功信息返回前端，但是存入的是redis，前端要提示用户，确定时间一个小时内,这里我不做处理了
            return result.success(test);
        }
    }


    @RequestMapping(value = "selectall",method = {RequestMethod.GET})
    public result selectall(Integer teahcerId,Integer size,Integer pagenum){
        PageData<Object> pageData=new PageData<>();
        logger.info("老师在查询所有要审批的上报信息");
        String key = String.valueOf(teahcerId);
        //获取 list的 长度1 即这个list 中 有多少 条 数据
        long end=redisUtil.lGetListSize(key);
        int become = (int) end;

        //Set<Object> all=redisUtil.sGet(key);
        //pagenum第几页 size 一页多少条信息
//        PageHelper.startPage(pagenum,size);
        //从redis 中 读取 数据 总量 写到 pagedata 这个类中
        pageData.setTotal(become);
        //从前端 获取 一页多少 数据 size 写到 pageData这个类中
        pageData.setSize(size);
        if(become % pageData.getSize()==0){
            //总页数 等于 全部数据 数  除于 每页的 条数
            pageData.setPageNum(become / pageData.getSize());
        }else {
            pageData.setPageNum(become / pageData.getSize()+1);
        }
        if(pageData.getPageNum()==0){
            pageData.setPageNum(1);
        }
        //redis中的list 分页 逻辑 如果为空也会返回空[]
        List<Object> list= redisUtil.lGet(key,size*(pagenum-1),(size*pagenum)-1);
        pageData.setResult(list);



//        PageInfo<Object> pageInfo=new PageInfo<>(list);
        //set集合转换成list 集合 放到 page分页器插件中
        //List<Object> list=new ArrayList<>(all);
        //pageHelper 只能放list集合进去

        if(pageData==null){
            return result.success("已经申报完了");
        }else {
            return result.success(pageData);
        }
    }



    @RequestMapping(value = "apply",method = {RequestMethod.POST})
    public result addTeacher(String type, @RequestBody Report report,String userEmail){
        logger.info("老师进行审批");
        String test="tongyi";
        if(type.equals(test)){
            //删除redis中的缓存
            Email email=new Email();
            List<String> emailUrl=new ArrayList<String>();
            emailUrl.add(userEmail);
            email.setToAddress(emailUrl);
            email.setSubject("审批回复");
            email.setContent("您的申请已经通过");
            mailService.sendMail(email);
            reportModel reportModel=new reportModel();
            reportModel.setName(report.getName());
            reportModel.setUserId(report.getUserId());
            reportModel.setWdo(report.getWdo());
            reportModel.setSec(report.getSec());
            reportModel.setEmail(userEmail);
            reportModel.setNowDate(report.getNowDate());
            reportModel.setHealthy(report.getHealthy());
            reportModel.setLive(report.getLive());
            userAdd teacher=userSecServices.selectUser(report.getUserId());
            String key = String.valueOf(teacher.getTeacherId());
//            redisUtil.del(report.getUserId());
            //删除list中的 值 count 移除几个数目
            redisUtil.lRemove(key,1,reportModel);
            return result.success(reportService.addSet(report));
        }else {
            Email email=new Email();
            List<String> emailUrl=new ArrayList<String>();
            emailUrl.add(userEmail);
            //接收邮件人 邮箱地址
            email.setToAddress(emailUrl);
            //文件标题
            email.setSubject("信息上报回复");
            //文件主要内容
            email.setContent("您的信息上报没通过<br><br>请登录系统查看");
            //删除redis中的缓存
            mailService.sendMail(email);
            reportModel reportModel=new reportModel();
            reportModel.setName(report.getName());
            reportModel.setUserId(report.getUserId());
            reportModel.setWdo(report.getWdo());
            reportModel.setSec(report.getSec());
            reportModel.setEmail(userEmail);
            reportModel.setNowDate(report.getNowDate());
            reportModel.setHealthy(report.getHealthy());
            reportModel.setLive(report.getLive());
            userAdd teacher =userSecServices.selectUser(report.getUserId());
            String key =String.valueOf(teacher.getTeacherId());
            redisUtil.lRemove(key,1,reportModel);
            //下面可以用websock在系统中给学生发信息，技术未成熟以后有时间再弄
            redisUtil.sSet("studentHasError",report);
            return result.fail("审批结果已经发送给学生了");
        }
    }


    //老师查询指定学生的请假信息,用@RequstBody 不知道为什么返回的string很奇怪 可能是序列化问题 以后处理，不然把学生学号放在头里面太危险了
    @RequestMapping(value = "/studentReport",method = {RequestMethod.GET})
    public result selectStudent(@Param("userId") String userId){
        logger.info("老师在审批对应学生的请假情况");
        return result.success(redisUtil.get(userId));
    }

    @RequestMapping(value = "leader",method = {RequestMethod.GET})
    public result leaderSelect(){
        logger.info("正在查看学院中的患病人信息");
        //获取redis中的set类型数据
        return result.success(redisUtil.sGet("studentHasError"));
    }

    //测试结果 如果在头里面 写的params 太长 会默认为字符串
    @RequestMapping(value = "/test",method = {RequestMethod.GET})
    public result test(@Param("id") Integer id){
        Integer hello=id;
        return result.success(redisUtil.sSet("helloInt",hello));
    }

    //今天上传未审批人数
    @RequestMapping(value = "/getallcount",method = {RequestMethod.GET})
    public result getcount(Integer teacherId){
        String key = String.valueOf(teacherId);
        return result.success(redisUtil.lGetListSize(key));
    }

    //判断是否有学生去了高危地区
    @RequestMapping(value = "/getwdocount",method = {RequestMethod.GET})
    public result getwdocount(Integer teacherId) throws NoSuchFieldException {
        String key = String.valueOf(teacherId);
        long size= redisUtil.lGetListSize(key);
        List<Object> test=redisUtil.lGet(key,0,size-1);
        int count=0;
        for (Object hello:test){
            reportModel entry=(reportModel) hello;
            String city=entry.getWdo();
            if(city.contains("荔湾区")){
                count++;
            }
        }
        return result.success(count);
    }

    //判断是否存在高危人数 以发热为主
    @RequestMapping(value = "/dengerlous",method = {RequestMethod.GET})
    public result dengerlous(Integer teacherId){
        String key=String.valueOf(teacherId);
        long size=redisUtil.lGetListSize(key);
        Integer count=0;
        List<Object> list=redisUtil.lGet(key,0,size-1);
        for (Object test:list){
            reportModel hello=(reportModel) test;
            if(hello.getHealthy().contains("发热")){
                count++;
            }
        }
        return result.success(count);
    }


    //区出每个对象提交的时间数据
    @RequestMapping(value = "/getUploadTime",method = {RequestMethod.GET})
    public result getUploadTime(Integer teacherId){
        String key=String.valueOf(teacherId);
        long size=redisUtil.lGetListSize(key);
        List<Object> time=new ArrayList<>();
        List<Object> list=redisUtil.lGet(key,0,size-1);
        for(Object test:list){
            reportModel hello=(reportModel) test;
            time.add(hello.getNowDate());
        }
        return result.success(time);
    }


}
